package cn.varin;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.junit.jupiter.api.Test;

public class MqttReceiveMessageTest {



    /**
     *
     *
     * String serverURI,(mqtt服务端地址)
     * String clientId,(客户端id)
     * MqttClientPersistence persistence（内存持久类）
     *
     *
     */
    public static String serviceURL= "tcp://varin.cn:1883";
    public static String clientId="varya_test_01";
    public static MqttClient client;
    public static String user="varya";
   public static String password= "123456";

    static {
        try {
            // 建立一个mqqt客户端类
            client = new MqttClient(serviceURL,clientId,new MemoryPersistence());
            MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
            mqttConnectOptions.setUserName(user);
            mqttConnectOptions.setPassword(password.toCharArray());
            client.connect(mqttConnectOptions);
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }


    // 接受消息
    @Test
    public void SendMessageTest() throws MqttException {
       client.subscribe("java_and_mqttx_conn",2);
       // 建立接收消息回调
        client.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable throwable) {
                // 连接丢失时调用
                System.out.println("cooection error");
            }

            @Override
            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                // 接收到消息时调用
                System.out.println("来自主题："+s);
                System.out.println("接收到的消息为："+new String(mqttMessage.getPayload()));
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                // 解释消息结束时调用
                System.out.println("deliveryComplete");
            }
        });
        // 为了保持test类的连接，建立一个死循环语句
        while (true);


    }


}
